﻿using System;
using System.IO;
using LoungeRepo.Contracts.EntityStore;

namespace LoungeRepo.EntityStore
{
    public partial class FilesystemEntityStore : IEntityStore
    {
        private readonly string rootFolder;


        public FilesystemEntityStore(string rootFolder)
        {
            this.rootFolder = rootFolder;
        }


        public void Store(IStreamedEntity streamedEntity)
        {
            try
            {
                using (var target = CreateEntityFile(streamedEntity))
                {
                    Store(target, streamedEntity);
                }
            }
            catch(Exception ex)
            {
                throw new EntityStoreException(string.Format("Error writing entiy '{0}/{1}' to entity store!", streamedEntity.Partition, streamedEntity.Id), ex);
            }
        }


        public IStreamedEntity Load(string id, string partition)
        {
            try
            {
                using (var source = OpenEntityFile(id, partition))
                {
                    IStreamedEntity se = Load(id, partition, source);
                    se.Blob.Seek(0, SeekOrigin.Begin);
                    return se;
                }
            }
            catch(Exception ex)
            {
                throw new EntityStoreException(string.Format("Error loading entity '{0}/{1}' from entity store!", partition, id), ex);
            }
        }


        public void Delete(string id, string partition)
        {
            try
            {
                var filename = CreateEntityFilename(id, partition);
                RetryConnectToFile(() =>
                                       {
                                           File.Delete(filename);
                                           return null;
                                       }
                    );
            }
            catch(Exception ex)
            {
                throw new EntityStoreException(string.Format("Error deleting entity '{0}/{1}' from entity store!", partition, id), ex);
            }
        }
    }
}
